package com.ws.shop.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.ws.shop.action.admin.AccessoryAction;
import com.ws.shop.bean.HtmlConfig;
import com.ws.shop.bean.Page;
import com.ws.shop.bean.SystemConfig;
import com.ws.shop.entity.Accessory;
import com.ws.shop.entity.Article;
import com.ws.shop.entity.ArticleCategories;
import com.ws.shop.entity.Auction;
import com.ws.shop.entity.Category;
import com.ws.shop.entity.Goods;
import com.ws.shop.entity.Links;
import com.ws.shop.entity.Mall;
import com.ws.shop.entity.Sunpic;
import com.ws.shop.service.ArticleCategoriesService;
import com.ws.shop.service.AuctionLogService;
import com.ws.shop.service.AuctionService;
import com.ws.shop.service.CategoryService;
import com.ws.shop.service.GoodsService;
import com.ws.shop.service.HtmlService;
import com.ws.shop.service.LinksService;
import com.ws.shop.service.MallService;
import com.ws.shop.service.SunpicService;
import com.ws.shop.util.SpringUtil;
import com.ws.shop.util.StringUtil;
import com.ws.shop.util.SystemConfigUtil;
import com.ws.shop.util.TemplateConfigUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * Service实现类 - 生成静态
 */

@Service(value="htmlService")
public class HtmlServiceImpl implements HtmlService {

	@Autowired
	private FreeMarkerConfigurer freemarkerManager;
	@Autowired
	private ArticleCategoriesService articleCategoriesService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private AuctionService auctionService;
	@Autowired
	private SunpicService sunpicService;
	@Autowired
	private AuctionLogService auctionLogService;
	@Autowired
	private LinksService linksService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private MallService mallService;
	
	public void buildHtml(String templateFilePath, String htmlFilePath, Map<String, Object> data) {
		try {
			Configuration configuration = freemarkerManager.getConfiguration();
			Template template = configuration.getTemplate(templateFilePath);
			File htmlFile = new File(SpringUtil.getRealPath(htmlFilePath));
			File htmlDirectory = htmlFile.getParentFile();
			if (!htmlDirectory.exists()) {
				htmlDirectory.mkdirs();
			}
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
			template.process(data, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 获取公共数据
	public Map<String, Object> getCommonData() {
		Map<String, Object> commonData = new HashMap<String, Object>();
		SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();
		String base = SpringUtil.getServletContext().getContextPath();
		if(base.endsWith("/")){
			base = base.substring(0,base.length()-1);
		}
		commonData.put("base", base);
		//系统配置
		commonData.put("systemConfig", SystemConfigUtil.getSystemConfig());
		//商品分类导航
		List<Category> categoryList = categoryService.findAllCategoryList();
		commonData.put("categoryList", categoryList);
		//底部文章导航
		List<ArticleCategories> bottomNavigationWithArticle = articleCategoriesService.findBottomNavigationWithArticle(SystemConfigUtil.getSystemConfig().getBottomNavigationCategories());
		commonData.put("bottomNavigationWithArticle", bottomNavigationWithArticle);
		//友情链接
		List<Links> linksList = linksService.findLinksList(1);
		commonData.put("linksList", linksList);
		return commonData;
	}
	
	public void indexBuildHtml() {
		HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.INDEX);
		Map<String, Object> data = getCommonData();
		String htmlFilePath = htmlConfig.getHtmlFilePath();
		String templateFilePath = htmlConfig.getTemplateFilePath();
		buildHtml(templateFilePath, htmlFilePath, data);
	}
	
	public void articleContentBuildHtml(Article article) {
		Map<String, Object> data = getCommonData();
		String htmlFilePath = article.getLink();
		if(article.getState() !=1 || StringUtil.isEmpty(htmlFilePath)){
			return;
		}
		data.put("article", article);
		List<ArticleCategories> articleCategoriesParentTree = articleCategoriesService.findArticleCategoriesParentTreeById(article.getCid());
		data.put("articleCategoriesParentTree", articleCategoriesParentTree);
		if(articleCategoriesParentTree.get(0).getType() == 1){
			
		}else if(articleCategoriesParentTree.get(0).getType() == 2 ){
			List<ArticleCategories> articleCategoriesWithArticleTree = articleCategoriesService.findChildArticleCategoriesWithArticleById(articleCategoriesParentTree.get(0).getId());
			data.put("articleCategoriesWithArticleTree", articleCategoriesWithArticleTree);
		}else if(articleCategoriesParentTree.get(0).getType() == 3){
			List<ArticleCategories> articleCategoriesWithArticleTree = articleCategoriesService.findChildArticleCategoriesWithArticleById(articleCategoriesParentTree.get(0).getId());
			data.put("articleCategoriesWithArticleTree", articleCategoriesWithArticleTree);
		}
		data.put("htmlFilePath", htmlFilePath);
		String templateFilePath = TemplateConfigUtil.ARTICLE_TEMPLATE_MAP.get(articleCategoriesParentTree.get(articleCategoriesParentTree.size()-1).getType()+"");
		buildHtml(templateFilePath, htmlFilePath, data);
	}
	
	public void auctionDetailBuildHtml(Auction auction){
		Map<String, Object> data = getCommonData();
		if(StringUtil.isEmpty(auction.getHtml())){
			HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.AUCTIOIN_DETAIL);
			String htmlFilePath = htmlConfig.getHtmlFilePath(auction.getId()+"");
			auction.setHtml(htmlFilePath);
			auctionService.updateHtml(auction.getId(), htmlFilePath);
		}
		Goods goods = goodsService.findGoodsById(auction.getGid());
		List<Accessory> accessoryList = goodsService.findAccessoryListByGoodsId(auction.getGid());
    	Page historyAuctionPage = auctionService.findAuctionListPage(1,4,auction.getCid(),3,auction.getIsfree());
    	List<Map<String,Object>> auctionLogList = auctionLogService.findAuctionLogList(0, 10, auction.getId());
    	if(auction.getState() == 4){
    		Sunpic sunpic = sunpicService.findSunpicByAid(auction.getId());
    		if(sunpic != null){
    			data.put("sunpic", sunpic);
    			List<Accessory> accessorySunpicList = sunpicService.findAccessoryListBySunpicId(sunpic.getId());
    			data.put("accessorySunpicList", accessorySunpicList);
    		}
    	}
    	data.put("auctionLogList", auctionLogList);
    	data.put("historyAuctionList", historyAuctionPage.getData());
    	data.put("auction", auction);
    	data.put("goods", goods);
    	data.put("accessoryList", accessoryList);
    	data.put("saveImagUrl", AccessoryAction.SAVE_IMAG_URL);
    	int state = auction.getState();
    	if(state >= 2)
    		state = 2;
    	String templateFilePath = TemplateConfigUtil.AUCTION_TEMPLATE_MAP.get(state+"");
		buildHtml(templateFilePath, auction.getHtml(), data);
	}
	
	public void mallDetailBuildHtml(Mall mall){
		Map<String, Object> data = getCommonData();
		if(StringUtil.isEmpty(mall.getHtml())){
			return;
		}
		Goods goods = goodsService.findGoodsById(mall.getGid());
		List<Accessory> accessoryList = goodsService.findAccessoryListByGoodsId(mall.getGid());
    	data.put("mall", mall);
    	data.put("goods", goods);
    	data.put("accessoryList", accessoryList);
    	data.put("saveImagUrl", AccessoryAction.SAVE_IMAG_URL);
    	String templateFilePath = TemplateConfigUtil.getHtmlConfig(HtmlConfig.MALL_DETAIL).getTemplateFilePath();
		buildHtml(templateFilePath, mall.getHtml(), data);
	}
	
	public void errorPageBuildHtml() {
		HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.ERROR_PAGE);
		Map<String, Object> data = getCommonData();
		data.put("errorContent", "系统出现异常，请与管理员联系！");
		String htmlFilePath = htmlConfig.getHtmlFilePath();
		String templateFilePath = htmlConfig.getTemplateFilePath();
		buildHtml(templateFilePath, htmlFilePath, data);
	}
	
	public void errorPageAccessDeniedBuildHtml() {
		HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.ERROR_PAGE);
		Map<String, Object> data = getCommonData();
		data.put("errorContent", "您无此访问权限！");
		String htmlFilePath = htmlConfig.getHtmlFilePath();
		String templateFilePath = htmlConfig.getTemplateFilePath();
		buildHtml(templateFilePath, htmlFilePath, data);
	}
	
	public void errorPage500BuildHtml() {
		HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.ERROR_PAGE_500);
		Map<String, Object> data = getCommonData();
		data.put("errorContent", "系统出现异常，请与管理员联系！");
		String htmlFilePath = htmlConfig.getHtmlFilePath();
		String templateFilePath = htmlConfig.getTemplateFilePath();
		buildHtml(templateFilePath, htmlFilePath, data);
	}
	
	public void errorPage404BuildHtml() {
		HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.ERROR_PAGE_404);
		Map<String, Object> data = getCommonData();
		data.put("errorContent", "您访问的页面不存在！");
		String htmlFilePath = htmlConfig.getHtmlFilePath();
		String templateFilePath = htmlConfig.getTemplateFilePath();
		buildHtml(templateFilePath, htmlFilePath, data);
	}
	
	public void errorPage403BuildHtml() {
		HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.ERROR_PAGE_403);
		Map<String, Object> data = getCommonData();
		data.put("errorContent", "系统出现异常，请与管理员联系！");
		String htmlFilePath = htmlConfig.getHtmlFilePath();
		String templateFilePath = htmlConfig.getTemplateFilePath();
		buildHtml(templateFilePath, htmlFilePath, data);
	}

}